<template>
  <div>
    <el-divider content-position="left"
      ><h3>
        字段映射
        <el-switch v-model="data.typeStatus" name="cdc"> </el-switch></h3
    ></el-divider>
    <div class="addBox" v-if="data.typeStatus">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="changeTableData"
      >
        <el-menu-item index="1">按库配置</el-menu-item>
        <el-menu-item index="2">按表配置</el-menu-item>
      </el-menu>
      <el-row style="margin: 10px auto" :gutter="12">
        <el-col :span="3">
          <el-button type="primary" size="small" @click="estimateResult = true"
            >导入评估结果</el-button
          >
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="small" @click="addMappingConfig"
            >添加</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" :key="activeIndex">
          <el-table
            border
            :data="
              data[activeIndex == 1 ? 'dbTypeMapping' : 'tableTypeMapping']
            "
            :key="estimateId"
            :height="300"
          >
            <el-table-column
              v-for="f in tableColOption"
              :key="f.childName + f.value"
              :prop="f.value"
              :label="f.label"
            >
              <template slot-scope="scope">
                {{ scope.row[f.childName][f.value] }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleEditEstimateConfig(scope.row, scope.$index)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDeleteEstimateConfig(scope.row, scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      :before-close="handleClose"
      title="添加字段映射"
      :visible.sync="dialogVisible"
      width="50%"
      v-if="dialogVisible"
    >
      <el-form ref="form" :rules="rules" :model="form">
        <el-row>
          <el-col :span="10">
            <el-form-item
              label-width="100px"
              class="custom-form-item"
              prop="taskName"
            >
              <template #label>
                <div class="font-700">配置条件</div>
              </template>
              <el-radio v-model="form.levae" label="1">按库</el-radio>
              <el-radio v-model="form.levae" label="2">按表</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="custom-form-item"
              prop="name"
              v-if="form.levae == '2'"
            >
              <template #label>
                <div class="font-700">选择表</div>
              </template>
              <el-select
                v-model="form.source.table"
                filterable
                allow-create
                default-first-option
                placeholder="请选择表"
                @change="handleSelectTable"
              >
                <el-option
                  v-for="item in data.tableTypeMapping"
                  :key="item.source.table"
                  :label="item.source.table"
                  :value="item.source.table"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-b">
          <el-col :span="12" style="border-right: 1px solid #ccc">
            <h3>源库：</h3>
            <el-col :span="20" v-if="form.levae == '2'">
              <el-form-item
                label-width="100px"
                label="字段名"
                class="custom-form-item"
                prop="name"
              >
                <template #label>
                  <div class="font-500">字段名</div>
                </template>
                <el-input
                  @input="handleSourcecName"
                  v-model="form.source.name"
                  placeholder="请选择源表字段名"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="类型"
                class="custom-form-item"
                prop="name"
              >
                <template #label>
                  <div class="font-500">类型</div>
                </template>

                <el-autocomplete
                  class="inline-input"
                  v-model="form.source.typeName"
                  :fetch-suggestions="sourceQuerySearch"
                  placeholder="请输入类型"
                  @select="(v) => handleSelect(v, 'source')"
                >
                  <template slot-scope="{ item }">
                    <ellipsisTooltip :tipText="item.desc" :value="item.value" />
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="长度"
                class="custom-form-item"
              >
                <template #label>
                  <div class="font-500">长度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写长度"
                  v-model="form.source.length"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="精度"
                class="custom-form-item"
                prop="precision"
              >
                <template #label>
                  <div class="font-500">精度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写精度"
                  v-model="form.source.precision"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="标度"
                class="custom-form-item"
                prop="scale"
              >
                <template #label>
                  <div class="font-500">标度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写标度"
                  v-model="form.source.scale"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="时间精度"
                class="custom-form-item"
                prop="timePrecision"
              >
                <template #label>
                  <div class="font-500">时间精度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写时间精度"
                  v-model="form.source.timePrecision"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="非空"
                class="custom-form-item"
                prop="nullable"
              >
                <template #label>
                  <div class="font-500">非空</div>
                </template>
                <el-select
                  v-model="form.source.nullable"
                  placeholder="请选择是否非空"
                >
                  <el-option
                    v-for="item in nullableOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="默认值"
                class="custom-form-item"
                prop="defaultValue"
              >
                <template #label>
                  <div class="font-500">默认值</div>
                </template>
                <el-input
                  type="text"
                  v-model="form.source.defaultValue"
                  placeholder="请填写默认值"
                />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <h3>目标库：</h3>
            <el-col :span="20" v-if="form.levae == '2'">
              <el-form-item
                label-width="100px"
                class="custom-form-item"
                prop="tableName"
              >
                <template #label>
                  <div class="font-500">字段名</div>
                </template>
                <el-input
                  type="text"
                  disabled
                  placeholder="请填写字段名"
                  v-model="form.sink.name"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="类型"
                class="custom-form-item"
                prop="name"
              >
                <template #label>
                  <div class="font-500">类型</div>
                </template>

                <el-autocomplete
                  class="inline-input"
                  v-model="form.sink.typeName"
                  :fetch-suggestions="sinkQuerySearch"
                  placeholder="请输入类型"
                  @select="(v) => handleSelect(v, 'sink')"
                >
                  <template slot-scope="{ item }">
                    <ellipsisTooltip :tipText="item.desc" :value="item.value" />
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="长度"
                class="custom-form-item"
              >
                <template #label>
                  <div class="font-500">长度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写长度"
                  v-model="form.sink.length"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="精度"
                class="custom-form-item"
                prop="precision"
              >
                <template #label>
                  <div class="font-500">精度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写精度"
                  v-model="form.sink.precision"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="标度"
                class="custom-form-item"
                prop="scale"
              >
                <template #label>
                  <div class="font-500">标度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写标度"
                  v-model="form.sink.scale"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="时间精度"
                class="custom-form-item"
                prop="timePrecision"
              >
                <template #label>
                  <div class="font-500">时间精度</div>
                </template>
                <el-input
                  type="text"
                  placeholder="请填写时间精度"
                  v-model="form.sink.timePrecision"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="非空"
                class="custom-form-item"
                prop="nullable"
              >
                <template #label>
                  <div class="font-500">非空</div>
                </template>
                <el-select
                  v-model="form.sink.nullable"
                  placeholder="请选择是否非空"
                >
                  <el-option
                    v-for="item in nullableOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label-width="100px"
                label="默认值"
                class="custom-form-item"
                prop="defaultValue"
              >
                <template #label>
                  <div class="font-500">默认值</div>
                </template>
                <el-input
                  type="text"
                  v-model="form.sink.defaultValue"
                  placeholder="请填写默认值"
                />
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="enterMapping">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择评估结果" :visible.sync="estimateResult" width="30%">
      <el-select v-model="estimateId" placeholder="请选择评估结果">
        <el-option
          v-for="item in estimateOverOption"
          :key="item.id"
          :label="item.taskName + item.startTime"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="estimateResult = false">取 消</el-button>
        <el-button type="primary" @click="handleEstimateOver">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Vue from "vue";
import tableData from "./typeMiappingData.js";
import { getListConfigDbTypes } from "@/api/console/datasourceInfo";
import EllipsisTooltip from "@/components/ToolTips";
import { getAppraiseTaskReportList } from "@/api/console/dataTaskLog";

export default {
  name: "typeMapping",
  components: { EllipsisTooltip },
  props: {
    data: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      estimateResult: false,
      tableColOption: null,
      rules: {},
      activeIndex: "1",
      nullableOptions: [
        {
          value: true,
          label: "是",
        },
        {
          value: false,
          label: "否",
        },
      ],
      options: [],
      form: null,
      dialogVisible: false,
      estimateOverOption: [],
      estimateId: null,
      list: [],
      sourceTypeNameOption: [],
      isEdit: false,
      sinkTypeNameOption: [],
    };
  },
  created() {
    this.reset();
    this.changeTableData(this.activeIndex);
    let { typeStatus, dbTypeMapping, tableTypeMapping } = this.$props.data;
    if (typeStatus == undefined) {
      Vue.set(this.$props.data, "typeStatus", false);
    }
    if (dbTypeMapping == undefined) {
      Vue.set(this.$props.data, "dbTypeMapping", []);
    }
    if (tableTypeMapping == undefined) {
      Vue.set(this.$props.data, "tableTypeMapping", []);
    }
  },
  async mounted() {
    let { start, end, sourceId } = this.$props.data;
    let { data } = await getAppraiseTaskReportList({
      taskType: `${start}-${end}`,
      databaseId: sourceId,
    });
    this.estimateOverOption = data;
  },
  methods: {
    handelcdcSwitchChange(v) {
      if (!v) {
        this.$props.data[`syncConf`] = [];
      }
    },
    changeTableData(v) {
      this.activeIndex = v;
      this.tableColOption =
        v == 1
          ? tableData.dataTypeMappingsDatabaseData
          : tableData.dataTypeMappingsTableData;
    },
    addMappingConfig() {
      this.reset();
      this.form.levae = this.activeIndex;
      this.dialogVisible = true;
      this.getTypeName();
    },
    reset() {
      this.form = {
        levae: "1",
        source: {
          table: "",
          nullable: true,
        },
        sink: {
          table: "",
          nullable: true,
        },
      };
    },
    handleSelectTable(v) {
      this.form.sink.table = v;
    },
    handleEstimateOver() {
      let tableTypeMapping = [];
      let dbTypeMapping = [];
      let item = JSON.parse(
        this.estimateOverOption.find((item) => item.id == this.estimateId)
          .taskResult
      ).data.tableResult;
      //   return;
      if (!item) {
        this.$message.error("暂无查询到校验结果");
        this.estimateResult = false;
        return 
      }
      item.databaseColMapping.forEach((f) => {
        f.nullable = !!f.nullable;
        dbTypeMapping.push({
          source: f,
          sink: {},
        });
      });
      Object.keys(item.tableColMapping).forEach((f) => {
        item.tableColMapping[f].forEach((g) => {
          g.nullable = !!g.nullable;
          tableTypeMapping.push({
            source: g,
            sink: {
              name: g.name,
              table: g.table,
            },
          });
        });
      });
      this.$props.data.tableTypeMapping = tableTypeMapping;
      this.$props.data.dbTypeMapping = dbTypeMapping;
      this.estimateResult = false;
    },
    async handleEditEstimateConfig(row, index) {
      this.form.sink = row.sink;
      this.form.source = row.source;
      this.form.levae = this.activeIndex;
      this.dialogVisible = true;
      this.isEdit = index + 1;
      this.getTypeName();
    },
    async getTypeName() {
      this.getTypeNameFn(this.$props.data.start, this.sourceTypeNameOption);
      this.getTypeNameFn(this.$props.data.end, this.sinkTypeNameOption);
    },
    async getTypeNameFn(type, data) {
      let res = await getListConfigDbTypes({
        catalogName: type,
      });
      res.data.groups.forEach((f) => {
        res.data.types[f].forEach((j) => {
          data.push({
            value: `${f}-${j.name}`,
            ...j,
          });
        });
      });
    },
    handleSelect(v, n) {
      this.form[n].typeName = v.name;
    },
    sourceQuerySearch(queryString, cb) {
      var restaurants = this.sourceTypeNameOption;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    sinkQuerySearch(queryString, cb) {
      var restaurants = this.sinkTypeNameOption;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.name
          .toLowerCase()
          .includes(queryString.toLowerCase());
      };
    },
    enterMapping() {
      if (this.isEdit > 0) {
        this.$props.data[
          this.form.levae == "1" ? "dbTypeMapping" : "tableTypeMapping"
        ][this.isEdit - 1] = this.form;
      } else {
        this.$props.data[
          this.form.levae == "1" ? "dbTypeMapping" : "tableTypeMapping"
        ].push(this.form);
      }
      this.reset();
      this.isEdit = false;
      this.dialogVisible = false;
      //   this.isEdit = true;
    },
    handleClose() {
      this.isEdit = false;
      this.dialogVisible = false;
    },
    handleSourcecName(v) {
      //   console.log(v);
      this.form.sink.name = v;
    },
    handleDeleteEstimateConfig(row, index) {
      this.$props.data[
        this.activeIndex == "1" ? "dbTypeMapping" : "tableTypeMapping"
      ].splice(index, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
h3 {
  font-weight: 600;
}

.margin-10 {
  margin-top: 15px;
}

.addBox {
  width: 95%;
  margin: 0 auto;
}

.font-500 {
  font-weight: 500;
}

.font-700 {
  font-weight: 700;
}

h3 {
  padding-left: 15px;
}

.row-b {
  border: 1px solid #ccc;
  width: 95%;
  margin: 0 auto;
}
</style>
